package com.kfm.hotel.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfm.hotel.config.HotelProperties;
import com.kfm.hotel.util.BaiduUtil;
import com.kfm.hotel.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/idcard")
public class IdCardController {

    @Autowired
    private HotelProperties properties;

    @PostMapping
    public R idcard(MultipartFile file) {
        // TODO() 从缓存中取出 accessToken
        // TODO() 如果没有 accessToken，就去获取 accessToken

        // 获取 accessToken
        String baiduApiKey = properties.getBaiduApiKey();
        String baiduSecretKey = properties.getBaiduSecretKey();
        try {
            /*
                1. 先判断缓存中是否有 accessToken
                2. 如果没有 accessToken，就去获取 accessToken，并存入缓存（设置过期时间）
                3. 如果有 accessToken，就直接使用
             */
//            String accessToken = BaiduUtil.getAccessToken(baiduApiKey, baiduSecretKey);
//            String idcard = BaiduUtil.idcard(file.getBytes(), accessToken);
             String idcard = """
                    {"words_result":{"姓名":{"location":{"top":46,"left":110,"width":77,"height":29},"words":"邹艳玲"},"民族":{"location":{"top":96,"left":233,"width":21,"height":25},"words":"汉"},"住址":{"location":{"top":192,"left":104,"width":256,"height":62},"words":"黑龙江省拜泉县兴华乡顺利村6组"},"公民身份号码":{"location":{"top":314,"left":205,"width":329,"height":30},"words":"230231198103291846"},"出生":{"location":{"top":142,"left":105,"width":204,"height":26},"words":"19810329"},"性别":{"location":{"top":98,"left":110,"width":23,"height":26},"words":"女"}},"words_result_num":6,"idcard_number_type":1,"image_status":"normal","log_id":1668448483061194859}
            """;
            return R.ok("成功", new ObjectMapper().readValue(idcard, Map.class));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.fail("识别失败");
    }
}
